//
//  ForgotPwdController.m
//  HarmonizePub
//
//  Created by rzhy on 16/9/8.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "ForgotPwdController.h"
#import "Utils.h"
#import "Config.h"
#import "JKCountDownButton.h"
#import "SVProgressHUD.h"

@interface ForgotPwdController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *phoneField;
@property (weak, nonatomic) IBOutlet UITextField *passWordField;
@property (weak, nonatomic) IBOutlet UITextField *confirmPwdField;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet JKCountDownButton *getCodeButton;
@property (weak, nonatomic) IBOutlet UIButton *determineButton;

@end

@implementation ForgotPwdController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"忘记密码";
    self.determineButton.layer.cornerRadius = 5.0f;
    self.determineButton.layer.masksToBounds = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setPhoneNum:(NSString *)phoneNum {
    _phoneNum = phoneNum;
    if (phoneNum.length) {
        self.phoneField.text = phoneNum;
        [self.passWordField becomeFirstResponder];
    } else
        [self.phoneField becomeFirstResponder];
}

#pragma mark - 验证码
- (IBAction)getCodeEvent:(JKCountDownButton *)sender {
    NSString *phoneNum = [self.phoneField.text stringRemoveSpecialSymbol:@" "];
    if (!phoneNum || [phoneNum isEqualToString:@""])
        [self setAlertViewWithMessage:@"请输入手机号码!"];
    else if (![Utils matchingTelNumber:phoneNum])
        [self setAlertViewWithMessage:@"请输入正确的手机号码!"];
    else {
        [self.view endEditing:NO];
        sender.enabled = NO;
        [sender startCountDownWithSecond:60];
        [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
            return [NSString stringWithFormat:@"剩余%d秒", (int)second];
        }];
        [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
            countDownButton.enabled = YES;
            return @"重新获取";
        }];
        [SVProgressHUD show];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
        NSDictionary *param = @{@"phone" : phoneNum, @"type" : @"2"};
        [HTTPSTool POST:XHCodePath params:param cookie:nil success:^(NSDictionary * _Nonnull JSON) {
            [SVProgressHUD dismiss];
            NSInteger result = [JSON[@"ret"] integerValue];
            if (result > 1) {
                [self setAlertViewWithMessage:JSON[@"msg"]];
                [sender stopCountDown];
            } else if (result == 1) {
                [ZYToast showBottomText:@"验证码发送成功!"];
                _determineButton.enabled = YES;
                _determineButton.backgroundColor = RGBAColor(125, 26, 31, 0.7);
            } else {
                [sender stopCountDown];
            }
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD dismiss];
            [sender stopCountDown];
        }];
    }
}

#pragma mark - 确定
- (IBAction)determineEvent:(UIButton *)sender {
    NSString *phone = self.phoneField.text;
    NSString *pwd = [self.passWordField.text stringRemoveSpecialSymbol:@" "];
    NSString *confirmPwd = [self.confirmPwdField.text stringRemoveSpecialSymbol:@" "];
    NSString *code = self.codeField.text;
    if (!phone || [phone isEqualToString:@""])
        [self setAlertViewWithMessage:@"请输入手机号码!"];
    else if (![Utils matchingTelNumber:phone])
        [self setAlertViewWithMessage:@"请输入正确的手机号码!"];
    else if (!pwd.length)
        [self setAlertViewWithMessage:@"请输入密码!"];
    else if (!confirmPwd.length)
        [self setAlertViewWithMessage:@"请确认密码!"];
    else if (![confirmPwd isEqualToString:pwd])
        [self setAlertViewWithMessage:@"两次输入的密码不一致，请重新输入！"];
    else if (!code.length)
        [self setAlertViewWithMessage:@"请输入验证码"];
    else {
        [SVProgressHUD show];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];
        NSDictionary *param = @{@"code" : code, @"userName" : phone, @"newPassword" : pwd};
        __unsafe_unretained ForgotPwdController *weakSelf = self;
        [HTTPSTool POST:XHForgetPassword params:param cookie:nil success:^(NSDictionary * _Nonnull JSON) {
//            XHLog(@"忘记密码 -> JSON: %@", JSON)
            [SVProgressHUD dismiss];
            NSInteger result = [JSON[@"ret"] integerValue];
            if (result > 1) {
                [self setAlertViewWithMessage:JSON[@"msg"]];
                [_getCodeButton stopCountDown];
            } else if (result == 1) {
                [ZYToast showOperationSuccess];
                if ([_delegate respondsToSelector:@selector(forgotPwdController:phone:passWord:)])
                    [_delegate forgotPwdController:weakSelf phone:phone passWord:pwd];
                [weakSelf dismissViewControllerAnimated:YES completion:nil];
            } else {
                [_getCodeButton stopCountDown];
            }
        } failure:^(NSError * _Nonnull error) {
            [SVProgressHUD dismiss];
            [_getCodeButton stopCountDown];
        }];
    }
}

#pragma mark - 返回
- (IBAction)back:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - textField delegat
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - AlertView
- (void)setAlertViewWithMessage:(NSString *)message {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提 示:" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:defaultAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:NO];
}

@end
